package pkg

import (
	"encoding/json"
	"github.com/gorilla/websocket"
	"log"
	"tie/global"
)

type Websocket struct {
}

type Message struct {
	UserId  int    `json:"userId"`
	SendId  int    `json:"sendId"`
	Content string `json:"content"`
}

func NewWebsocket() *Websocket {
	return &Websocket{}
}

func ReadMessage(node global.Node) {
	for {
		_, message, err := node.Conn.ReadMessage()
		if err != nil {
			log.Println(err)
			return
		}
		var msg Message
		err = json.Unmarshal(message, &msg)
		if err != nil {
			node.Data <- []byte("消息类型错误")
			return
		}
		if n, ok := global.ClientMap[int64(msg.SendId)]; ok {
			n.Data <- message
		}
	}
}

func WriteMessage(node global.Node) {
	for {
		data := <-node.Data
		node.Conn.WriteMessage(websocket.TextMessage, data)
	}
}
